//
//  QMADownloadDelegateImp.m
//  QQMiniGameSDKDemo
//
//  Created by Goyoungs on 2023/4/14.
//

#import "QMADownloadDelegateImp.h"

@implementation QMADownloadDelegateImp

/// 下载协议，宿主可自己替换
/// - Parameters:
///   - downloadInfo: 下载链接信息
///   - completionHandler: 下载成功回调
///   - progressHandler: 进度回调
- (void)downloadInfo:(QQDownloadInfo *)downloadInfo
   completionHandler:(void (^)(NSString *filePath, NSError *error))completionHandler
     progressHandler:(void (^_Nullable)(long long downloadedBytes, long long totalBytesExpected))progressHandler {
    NSURL *downloadURL = [NSURL URLWithString:downloadInfo.url];
    [[[NSURLSession sharedSession] dataTaskWithURL:downloadURL
                                 completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError *_Nullable error) {
        if (error) {
            if (completionHandler) {
                completionHandler(nil, error);
            }
            return;
        }
        
        if ([response isKindOfClass:[NSHTTPURLResponse class]] == NO) {
            NSError *rspErr = QMALocalError(QMAMiniAppErrorDomain, QMAMiniAppErrorResponseInvalid);
            if (completionHandler) {
                completionHandler(nil, rspErr);
            }
            return;
        }
        
        NSString *tmpPath = NSTemporaryDirectory();
        NSString *dataPath =
        [tmpPath stringByAppendingPathComponent:[NSString stringWithFormat:@"data_%u.%@", arc4random(), @"wxapkg"]];
        NSError *fileErr = nil;
        [data writeToFile:dataPath options:NSDataWritingAtomic error:&fileErr];
        
        if (fileErr) {
            if (completionHandler) {
                completionHandler(nil, fileErr);
            }
            return;
        }
        
        if (completionHandler) {
            completionHandler(dataPath, nil);
        }
    }] resume];
}

@end
